package com.jdy.haoduoai.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.VideoView;

import com.jdy.haoduoai.Constant;
import com.jdy.haoduoai.EventWatcher;
import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.LeMachine;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.socket.SocketInputThread;
import com.jdy.haoduoai.socket.SocketThreadManager;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.PathUtil;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.tencent.android.tpush.XGPushClickedResult;
import com.tencent.android.tpush.XGPushManager;
import com.umeng.analytics.MobclickAgent;
import com.umeng.analytics.MobclickAgent.EScenarioType;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.StringTokenizer;

//import com.jdy.haoduoai.R;

/**
 * 
 * @author Hufei
 * 
 */
public class SplashActivity extends BaseActivity implements
    OnCompletionListener {

  private static final String TAG = SplashActivity.class.getSimpleName();

  @InjectView(id = R.id.myvideoview)
  private VideoView mVideoView;
  @InjectView(id = R.id.tv_jump, click = true)
  private TextView tv_jump;
  @InjectView(id = R.id.placeholder, click = true)
  private View placeholder;

  private boolean bEnterGoToNextFunc = false;
  private boolean bInCheck;
  private Handler handler = new Handler();

  @SuppressWarnings({ "deprecation" })
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash_xxb);
    hideTitleView();
    tv_jump.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    tv_jump.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {

        if (mVideoView.isPlaying()) {
          mVideoView.stopPlayback();
        }

        if (!bInCheck) {
          jumpSplashPage();
        }

      }
    });

    XGPushClickedResult result = XGPushManager.onActivityStarted(this);
    if (result != null) { // 如果result为null就说明通知不是来自Xinge
      String customContent = result.getCustomContent();
      // 解析自定义key-value
      if (customContent != null && customContent.length() != 0) {
        // customContent 是服务端传过来的key-value值，在这里根据需求解析处理
        finish();
      }
    }

    MobclickAgent.setDebugMode(true);

    MobclickAgent.enableEncrypt(true);
    // SDK在统计Fragment时，需要关闭Activity自带的页面统计，
    // 然后在每个页面中重新集成页面统计的代码(包括调用了 onResume 和 onPause 的Activity)。
    MobclickAgent.openActivityDurationTrack(false);
    MobclickAgent.setScenarioType(this, EScenarioType.E_UM_NORMAL);

    // MobclickAgent.updateOnlineConfig(this);
    enableNetworkChangeListener();
  }

  @Override
  protected void onNetworkAvailable() {

  }

  @Override
  protected void onNetworkDisconnect() {
    super.onNetworkDisconnect();
    toastShow("请检查网络连接");
  }

  @Override
  public void onPause() {
    super.onPause();
    MobclickAgent.onPageEnd(TAG);
    MobclickAgent.onPause(this);
  }

  @Override
  protected void onResume() {
    super.onResume();
    MobclickAgent.onPageStart(TAG);
    MobclickAgent.onResume(this);

    if (!getWelcomeValue()) {
      startProductTour();
      finish();
    } else {
      Intent originalIntent = getIntent();
      if (originalIntent != null) {
        int i = originalIntent.getIntExtra("comefromwelcomepage", -1);
        if (i == 1) {
          SharedPreferences prefs = this.getSharedPreferences(
              Constant.USER_INFO, Context.MODE_PRIVATE);
          String tel = prefs.getString(Constant.TEL, "");
          String pwd = prefs.getString(Constant.PWD, "");

          if (Tools.isEmpty(tel) || Tools.isEmpty(pwd)) {
            LeConfig.isLogin = false;
            bInCheck = false;

            Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);

            finish();
          } else {
            placeholder.setVisibility(View.VISIBLE);
            playStartupVideo();
          }
        } else {
          placeholder.setVisibility(View.VISIBLE);
          playStartupVideo();
        }
      } else {
        placeholder.setVisibility(View.VISIBLE);
        playStartupVideo();
      }
    }
  }

  private void startProductTour() {
    startActivity(new Intent(this, ProductTourActivity.class));
    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
  }

  private void playStartupVideo() {
    String uriVideo = "android.resource://" + getPackageName() + "/"
        + R.raw.startup_animation;

    MediaController mc = new MediaController(this);
    mc.setAnchorView(mVideoView);
    mc.setMediaPlayer(mVideoView);
    final Uri video = Uri.parse(uriVideo);

    mVideoView.setVideoURI(video);
    mVideoView.start();
    mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
      @Override
      public void onPrepared(MediaPlayer mp) {

        mp.setOnInfoListener(new MediaPlayer.OnInfoListener() {
          @Override
          public boolean onInfo(MediaPlayer mp, int what, int extra) {
            if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
              placeholder.setVisibility(View.GONE);

              duration = mVideoView.getDuration();

              if (duration > 0) {
                tv_jump.setVisibility(View.VISIBLE);

                new CountDownTimer(duration, 1000) {
                  @Override
                  public void onTick(long millisUntilFinished) {
                    tv_jump.setText("跳过" + millisUntilFinished / 1000 + "S");
                  }

                  @Override
                  public void onFinish() {
                    tv_jump.setText("跳过" + 0 + "S");
                    tv_jump.setVisibility(View.GONE);
                  }
                }.start();
              }

              return true;
            }
            return false;
          }
        });

      }
    });
    mVideoView.setOnCompletionListener(SplashActivity.this);

  }

  int duration;

  // private void initUmeng() {
  // MobclickAgent.setDebugMode(true);
  // // AnalyticsConfig.enableEncrypt(true);
  // MobclickAgent.enableEncrypt(true);
  // // SDK在统计Fragment时，需要关闭Activity自带的页面统计，
  // // 然后在每个页面中重新集成页面统计的代码(包括调用了 onResume 和 onPause 的Activity)。
  // MobclickAgent.openActivityDurationTrack(false);
  //
  // MobclickAgent.setScenarioType(this, EScenarioType.E_UM_NORMAL);
  //
  // // MobclickAgent.setAutoLocation(true);
  // // MobclickAgent.setSessionContinueMillis(1000);
  // // MobclickAgent.updateOnlineConfig(this);
  // }

  private boolean getWelcomeValue() {
    SharedPreferences prefs = this.getSharedPreferences(Constant.WELCOME_PAGE,
        Context.MODE_PRIVATE);
    return prefs.getBoolean(Constant.HAS_ILLUSTRATED, false);
  }

  private void quickLogin() {
    Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    startActivity(intent);
    finish();
  }

  /**
   * 跳过
   */
  private void jumpSplashPage() {
    bInCheck = true;

    SharedPreferences prefs = this.getSharedPreferences(Constant.USER_INFO,
        Context.MODE_PRIVATE);
    String tel = prefs.getString(Constant.TEL, "");
    String pwd = prefs.getString(Constant.PWD, "");

    if (Tools.isEmpty(tel) || Tools.isEmpty(pwd)) {
      LeConfig.isLogin = false;
      bInCheck = false;

      Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
      intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
      startActivity(intent);

      finish();
    } else {
      if (Tools.isNetworkAvailable(SplashActivity.this)) {
        silentLogin();
      } else {
        Intent intent = new Intent(SplashActivity.this, MainActivity.class);
        intent.putExtra("nonetwork", true);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);

        bInCheck = false;

        finish();
      }
    }
  }

  private void checkLogin() {
    bInCheck = true;

    SharedPreferences prefs = this.getSharedPreferences(Constant.USER_INFO,
        Context.MODE_PRIVATE);
    String tel = prefs.getString(Constant.TEL, "");
    String pwd = prefs.getString(Constant.PWD, "");

    if (Tools.isEmpty(tel) || Tools.isEmpty(pwd)) { // jump to login
      LeConfig.isLogin = false;
      handler.postDelayed(new Runnable() {
        @Override
        public void run() {
          bInCheck = false;

          Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
          intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
          startActivity(intent);

          finish();
        }
      }, 1500);
    } else {
      handler.postDelayed(new Runnable() {
        @Override
        public void run() {
          if (Tools.isNetworkAvailable(SplashActivity.this)) {
            silentLogin();
          } else {
            Intent intent = new Intent(SplashActivity.this, MainActivity.class);
            intent.putExtra("nonetwork", true);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);

            bInCheck = false;

            finish();
          }

        }
      }, 1200);

    }
  }

  private void doPageRoute() {
    if (LeConfig.isLogin) {
      if (LeConfig.isDeviceBinded) {
        if (LeConfig.isInfoFilled) {
          if (LeConfig.isDeviceActivated) {

          } else {
            // TODO
          }

          // Intent t2 = new Intent(this, PainPointSelectActivity.class);
          // startActivity(t2);

          // Intent intent = new Intent(this, PainPointSelectActivity.class);
          // intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
          // startActivity(intent);
          Intent intent = new Intent(this, MainActivity.class);
          intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
          startActivity(intent);

          finish();
        } else {
          Intent t = new Intent(SplashActivity.this,
              FillInfoPopupActivity.class);
          startActivity(t);
          finish();
        }
      } else {
        Intent t = new Intent(SplashActivity.this, ConnectWifiActivity.class);
        startActivity(t);
        finish();
      }
    } else {
      // TODO
    }
  }

  private void silentLogin() {

    new CustomAsyncTask(this, new IAsyncTask() {

      @Override
      public ResponseResult doInbackground(Activity activity) {
        SharedPreferences prefs = activity.getSharedPreferences(
            Constant.USER_INFO, Context.MODE_PRIVATE);

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_MOBILE_I, prefs.getString(Constant.TEL, ""));
        param_.put(HttpUtils.TAG_PWD_I, prefs.getString(Constant.PWD, ""));
        param_.put(HttpUtils.TAG_PLATFORM_I, "android");
        param_.put(HttpUtils.TAG_TOKEN_I, "test");
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequestEncrypt(HttpUtils.API_URL
            + HttpUtils.LOGIN_METHOD_POST, param_, HttpUtils.TAG_POST_REQUEST);
      }

      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        MobclickAgent.onEvent(SplashActivity.this,
            EventWatcher.EVENT_XIAOXIAOBAN_LOGIN);

        if (result.isSuccess() && Tools.isNotNullStr(result.data)) {
          LeConfig.isLogin = true;
          SocketInputThread.kickOffline = false;

          LeUser lu = JsonSerializer.getInstance().deserialize(result.data,
              LeUser.class);

          LeMachine lbaby = null;
          if (lu != null) {
            lbaby = lu.machine;
          }

          LeXiaoXiaoBanApp.getInstance().setBaby(lbaby);

          // 是否已经绑定设备
          if (lbaby != null && !lbaby.toString().equals("null")
              && Tools.isNotEmpty(lbaby.id)) {
            LeConfig.isDeviceBinded = true;
            LeConfig.MAC_ID = lbaby.id;
            LeConfig.babyname = lbaby.name;

            // 宝宝头像
            getBabyAvatar(lbaby.avatar);

            // 检测设备版本
            // checkDeviceVersion(lbaby.version);

            // socket地址
            String url = lbaby.ip;
            if (Tools.isNotNullStr(url)) {
              StringTokenizer tokens = new StringTokenizer(url, ":");
              LeConfig.g_ServerIP = tokens.nextToken();
              LeConfig.FILE_PORT = Integer.parseInt(tokens.nextToken());
              // startService(new Intent(SplashActivity.this,
              // LeSocketManagerService.class));

               SocketThreadManager sss = SocketThreadManager.getInstance();

              // ImHelper ih = LeXiaoXiaoBanApp
            }

            if (lu != null && Tools.isNotEmpty(lu.nickname)
                && Tools.isNotEmpty(lbaby.name)) {
              LeConfig.isInfoFilled = true;

              if (Tools.isNotEmpty(lbaby.activate)
                  && !lbaby.activate.toString().equals("null")) {
                LeConfig.isDeviceActivated = !lbaby.activate.is_expired;
                LeConfig.expiredAt = lbaby.activate.expired_at;
              }
            } else {
              LeConfig.isInfoFilled = false;
            }

          } else {
            LeConfig.isDeviceBinded = false;
          }

          if (lu != null) {
            LeConfig.PHONE_NUM = lu.id;
            LeConfig.nickname = lu.nickname;
          }

          LeXiaoXiaoBanApp.getInstance().setUser(lu);
          Tools.saveLeUser(lu);
          Tools.saveLeBaby(lbaby);

          Intent intent = new Intent("com.jdy.haoduoai.activity.login");
          sendBroadcast(intent);

          {
            dismissLoading();

            MobclickAgent.onProfileSignIn(LeConfig.PHONE_NUM);

            toastShow("登录成功!");
            doPageRoute();
          }

          bInCheck = false;
        } else { // 登录失败
          bInCheck = false;
          if (Tools.isNotNullStr(result.data)) {
            toastShow(result.data);
          }

          Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
          intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
          startActivity(intent);

          finish();
        }

      }
    }).execute();
  }

  private void getBabyAvatar(String remoteBabyAvatar) {
    if (Tools.isEmpty(remoteBabyAvatar)) {
      return;
    }

    new AsyncTask<String, Void, Bitmap>() {
      @Override
      protected void onPostExecute(Bitmap result) {
        if (result != null) {
          String path = PathUtil.getBabyAvatarPath(getApplicationContext());
          FileOutputStream out = null;
          File babyAvatarFile = new File(path);
          try {
            out = new FileOutputStream(babyAvatarFile);
            result.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is
                                                                  // your
                                                                  // Bitmap
                                                                  // instance
            // PNG is a lossless format, the compression factor (100) is
            // ignored
            SharedPreferences prefs = getSharedPreferences(Constant.USER_INFO,
                Context.MODE_PRIVATE);
            Uri babyAvatarUri = Uri.fromFile(babyAvatarFile);
            prefs.edit()
                .putString(Constant.BABY_AVATAR, babyAvatarUri.toString())
                .apply();
          } catch (Exception e) {
            e.printStackTrace();
          } finally {
            try {
              if (out != null) {
                out.close();
              }
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
      }

      @Override
      protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];

        Bitmap resultImage = null;

        URL url;
        try {
          url = new URL(urldisplay);

          HttpURLConnection urlConnection = (HttpURLConnection) url
              .openConnection();

          urlConnection.setRequestMethod("GET");
          // urlConnection.setDoOutput(true);

          urlConnection.connect();

          InputStream in = urlConnection.getInputStream();

          // InputStream in = new java.net.URL(urldisplay).openStream();
          resultImage = BitmapFactory.decodeStream(in);

        } catch (MalformedURLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        return resultImage;
      }
    }.execute(remoteBabyAvatar);

    // }
  }

  /**
   * 设备升级提示
   * 
   * @param version
   */
  // public void checkDeviceVersion(String version) {
  // if (Tools.isNotEmpty(version)) {
  // try {
  // int currentDeviceVersion = Integer.valueOf(version.replaceAll("\\D+",
  // ""));
  // LeConfig.CURRENT_DEVICE_VERSION = currentDeviceVersion;
  // if (currentDeviceVersion < 201 && !LeConfig.DEBUG_MODE) {
  // LeConfig.isDeviceVersionMatch = false;
  // CustomOneBtnDialog.Builder cdb = new CustomOneBtnDialog.Builder(
  // getApplicationContext()).setTitle("升级提示")
  // .setMessage("请更新您的小小班设备")
  // .setPositiveButton("确定", new DialogInterface.OnClickListener() {
  //
  // @Override
  // public void onClick(DialogInterface dialog, int which) {
  // dialog.dismiss();
  // }
  // });
  // CustomOneBtnDialog cd = cdb.create();
  // cd.setCancelable(false);
  // cd.setCanceledOnTouchOutside(false);
  // cd.show();
  // } else {
  // LeConfig.isDeviceVersionMatch = true;
  // }
  // } catch (NumberFormatException nfe) {
  // return;
  // }
  // }
  // }

  private int totalMonth;

  /**
   * 判断宝宝年龄
   */
  private void checkBabyAge() {
    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
    if (lu != null && Tools.isNotEmpty(lu.machine)) {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

      try {
        Calendar bef = Calendar.getInstance();
        bef.setTime(sdf.parse(lu.machine.dob));

        int month = Calendar.getInstance().get(Calendar.MONTH)
            - bef.get(Calendar.MONTH);

        int year = Calendar.getInstance().get(Calendar.YEAR)
            - bef.get(Calendar.YEAR);

        totalMonth = year * 12 + month;
        if (totalMonth == 0) {
          totalMonth = 1;
        }

      } catch (Exception e) {
        // TODO: handle exception
      }
    }
  }

  // @SuppressWarnings("unused")
  // private void goToMainActivity() {
  // if (bEnterGoToNextFunc) {
  // return;
  // }
  //
  // checkBabyAge();
  // bEnterGoToNextFunc = true;
  //
  // // 第一次启动app，在绑定设备完成后出现? 待确定
  // // Intent t = new Intent(this, AttractNewRepelActivity.class);
  // // startActivity(t);
  //
  // if (totalMonth >= (5 * 12 + 6)) { // 5岁半以上
  // Intent t = new Intent(this, AttractNewRepelActivity.class);
  // startActivity(t);
  // } else {
  // startActivity(new Intent(this, AbilityTestActivity.class));
  // }
  //
  // //
  // if (mOverridePendingTransition != null) {
  // try {
  // mOverridePendingTransition.invoke(this, R.anim.activity_fade_out,
  // R.anim.activity_remain_stay);
  // } catch (InvocationTargetException ite) {
  // } catch (IllegalAccessException ie) {
  // }
  // }
  //
  // finish();
  // }
  @Override
  public void finish() {
    super.finish();
    activityAnimFadeout();
  }

  @Override
  protected void onDestroy() {
    if (handler != null) {
      handler.removeCallbacksAndMessages(null);
      handler = null;
    }

    disableNetworkChangeListener();
    super.onDestroy();
  }

  /*
   * (non-Javadoc)
   * 
   * @see
   * android.media.MediaPlayer.OnCompletionListener#onCompletion(android.media
   * .MediaPlayer)
   */
  @Override
  public void onCompletion(MediaPlayer mp) {
    checkLogin();
  }
}
